<?php
namespace Admin\Controller;

use Think\Cache\Driver\Redis;

class AuthController extends CommonController {

    const APPID = 'wxff511737a867ae35';
    const AppSecret = 'f45525f46e400021f3fbdf1d6eab998f';
    const Token = 'yuanyi2018';
    const Key = 'dH0HWACjxmul871USoBbHRC2qi01bEgWKJVJizLxT12';
    const URL = 'https://api.beikg.cn';

    /**
     * 获取第三方授权component_access_token
     */
    private function component_access_token(){

        $redis = new Redis();

        $component_access_token = $redis->get('component_access_token');

        if (!empty($component_access_token)){
            return $component_access_token;
        }

        $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";

        $ticket = $redis->get('ticket');

        $data = array(
            'component_appid'=>self::APPID,
            'component_appsecret'=>self::AppSecret,
            'component_verify_ticket'=>$ticket,
        );

        $res = $this->getcomponent($url,json_encode($data));

        $redis->set('component_access_token',$res['component_access_token'],$res['expires_in']);

        return $res['component_access_token'];

    }

    /**
     * 获取预授权码
     */
    public function pre_auth_code(){

        $redis = new Redis();

        $pre_auth_code = $redis->get('pre_auth_code');

        $component_access_token = $this->component_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=$component_access_token";

        $data = array(
            'component_appid'=>self::APPID,
        );

        $res = $this->getcomponent($url,json_encode($data));

        $redis->set('pre_auth_code',$res['pre_auth_code'],$res['expires_in']);

        return $res['pre_auth_code'];

    }

    /**
     * 授权页
     */

    public function auth(){

        $component_appid = self::APPID;
        $pre_auth_code = $this->pre_auth_code();
        $appid = "wx752ceb8e4e1200e3";//测试的
        $info = M('auth_app')->where(array('appid'=>$appid))->find();
        $redirect_uri = "https://api.beikg.cn/Admin/Auth/getcode/appid/$appid";
        $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=$component_appid&pre_auth_code=$pre_auth_code&redirect_uri=$redirect_uri";

        $this->assign('info',$info);
        $this->assign('appid',$appid);
        $this->assign('url',$url);

        $this->display('auth');

    }

    /**
     * 授权页
     */

    public function lyricist2(){

        $component_appid = self::APPID;
        $pre_auth_code = $this->pre_auth_code();

        $appid = "wxe180236290032484"; //疯狂填词王奖金版2

        $info = M('auth_app')->where(array('appid'=>$appid))->find();

        $redirect_uri = "https://api.beikg.cn/Admin/Auth/getcode/appid/$appid";
        $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=$component_appid&pre_auth_code=$pre_auth_code&redirect_uri=$redirect_uri";


        $this->assign('appid',$appid);
        $this->assign('url',$url);
        $this->assign('info',$info);
        $this->display('lyricist2');

    }

    /**
     * 授权页
     */

    public function lyricist(){

        $component_appid = self::APPID;
        $pre_auth_code = $this->pre_auth_code();

        $appid = "wx402ce3c8d9a9de9b"; //疯狂填词王奖金版

        $info = M('auth_app')->where(array('appid'=>$appid))->find();

        $redirect_uri = "https://api.beikg.cn/Admin/Auth/getcode/appid/$appid";
        $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=$component_appid&pre_auth_code=$pre_auth_code&redirect_uri=$redirect_uri";


        $this->assign('info',$info);
        $this->assign('appid',$appid);
        $this->assign('url',$url);

        $this->display('lyricist');

    }

    public function applog()
    {
        $appid = I('get.appid','','htmlspecialchars');

        if (empty($appid)){
            $msg['state']   =   -1;
            $msg['error']   =   '非法请求';
            $this->ajaxReturn ($msg,'JSON');
        }

        $info = M('auth_app')->where(array('appid'=>$appid))->find();


        $this->assign('info',$info);
        $this->display('applog');

    }

    /**
     * 授权回调
     *
     */
    public function getcode(){

        $authcode = $_GET['auth_code'];

        $expires_in = $_GET['expires_in'];

        $appid = $_GET['appid'];

        if (!empty($authcode)){

            $redis = new Redis();
            $name = $appid.'auth_code';
            $redis->set($name,$authcode,$expires_in);


            switch ($appid){
                case "wx752ceb8e4e1200e3":
                    $url = "https://api.beikg.cn/Admin/Auth/auth"; //测试的
                    break;
                case "wxe180236290032484"://疯狂填词王奖金版2
                    $url = "https://api.beikg.cn/Admin/Auth/lyricist2";
                    break;
                case "wx402ce3c8d9a9de9b"://疯狂填词王奖金版
                    $url = "https://api.beikg.cn/Admin/Auth/lyricist";
                    break;

            }

            header('location:'.$url);

        }

    }

    /**
     * 获取小程序授权authorizer_access_token
     */
    private function authorizer_access_token($appid){

        $redis = new Redis();

        $authorizer_access_tokenname = $appid.'authorizer_access_token';

        $authorizer_access_token = $redis->get($authorizer_access_tokenname);

        if (!empty($authorizer_access_token)){
            return $authorizer_access_token;
        }

        $name = $appid.'auth_code';
        $component_appid = self::APPID;

        $authorization_code = $redis->get($name);

        $component_access_token = $this->component_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=$component_access_token";
        $postdata = array(
            'component_appid' =>$component_appid,
            'authorization_code' =>$authorization_code,
        );
        $postdata = json_encode($postdata);
        $authtoken = $this->getcomponent($url,$postdata);

        $authorizer_appid = $authtoken[authorization_info][authorizer_appid];
        $authorizer_access_token = $authtoken[authorization_info][authorizer_access_token];
        $expires_in = $authtoken[authorization_info][expires_in];
        $authorizer_refresh_token = $authtoken[authorization_info][authorizer_refresh_token];


        $authorizer_refresh_tokenname = $appid.'authorizer_refresh_token';

        $redis->set($authorizer_access_tokenname,$authorizer_access_token,$expires_in);
        $redis->set($authorizer_refresh_tokenname,$authorizer_refresh_token,30*24*3600);

       return $authorizer_access_token;

    }

    /**
     * 刷新小程序授权authorizer_access_token
     * @param $authorizer_appid
     * @return mixed
     */
    private function refreshtoken($authorizer_appid){

        $redis = new Redis();

        $authorizer_refresh_tokenname = $authorizer_appid.'authorizer_refresh_token';

        $authorizer_access_tokenname = $authorizer_appid.'authorizer_access_token';

        $authorizer_access_token = $redis->get($authorizer_access_tokenname);

        if (!empty($authorizer_access_token)){
            return $authorizer_access_token;
        }

        $authorizer_refresh_token = $redis->get($authorizer_refresh_tokenname);

        if (empty($authorizer_refresh_token)){
            return $this->authorizer_access_token($authorizer_appid);
        }

        $component_appid = self::APPID;

        $component_access_token = $this->component_access_token();

        $url ="https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=$component_access_token";
        $postdata = array(
            'component_appid' =>$component_appid,
            'authorizer_appid' => $authorizer_appid,
            'authorizer_refresh_token' =>$authorizer_refresh_token,
        );
        $postdata = json_encode($postdata);
        $authtoken = $this->getcomponent($url,$postdata);

        $authorizer_access_token = $authtoken[authorizer_access_token];
        $expires_in = $authtoken[expires_in];
        $authorizer_refresh_token = $authtoken[authorizer_refresh_token];

        if (empty($authorizer_access_token)){
            return $this->authorizer_access_token($authorizer_appid);
        }



        $redis->set($authorizer_access_tokenname,$authorizer_access_token,$expires_in);
        $redis->set($authorizer_refresh_tokenname,$authorizer_refresh_token,30*24*3600);

        return $authorizer_access_token;

    }

    /**修改服务器
     * @param $user
     * @param $mid
     * @return mixed
     */
    public function modifyserver($appid){


        $authorizer_access_token = $this->refreshtoken($appid);

        $url = "https://api.weixin.qq.com/wxa/modify_domain?access_token=$authorizer_access_token";
        $hurl = self::URL;
        $postdata = array(
            "action" => "set",
            "requestdomain"=>array(
                $hurl
            ),
            "wsrequestdomain"=>'',
            "uploaddomain"=>array(
                $hurl
            ),
            "downloaddomain"=>array(
                $hurl
            ),
        );
        $postdata = json_encode($postdata,JSON_UNESCAPED_SLASHES);
        $check = $this->getcomponent($url,$postdata);
        return $check;
    }

    //上传代码
    public function uploadcode(){

      $appid = I('post.appid','','htmlspecialchars');
        $appname = I('post.appname','','htmlspecialchars');
        $template_id = I('post.template_id','','htmlspecialchars');
        $user_version = I('post.user_version','','htmlspecialchars');
        $user_desc = I('post.user_desc','','htmlspecialchars');


      $this->modifyserver($appid);  //修改服务器
      $accesstoken = $this->refreshtoken($appid);

        $url = "https://api.weixin.qq.com/wxa/commit?access_token=$accesstoken";
        $ext = '{
  "extEnable": true,
  "extAppid": "'.$appid.'",
  "ext": {
    "name": "'.$appname.'",
    "attr": {
      "host": "open.weixin.qq.com",
      "users": [
      ]
    }
  },
  "extPages": {
  },
  "window":{
  },
  "networkTimeout": {
  }
}';


        $postdata = array(
            "template_id" =>$template_id,
            "ext_json"  =>"$ext",
            "user_version" =>$user_version,
            "user_desc" =>$user_desc,
        );
        $postdata = json_encode($postdata,JSON_UNESCAPED_UNICODE);
        $check = $this->getcomponent($url,$postdata);

        $errcode = $check[errcode];

        if ($errcode==0){
            $data = array(
                'user_desc'=>$user_desc,
                'user_version'=>$user_version,
                'appid'=>$appid,
                'appname'=>$appname,
                'template_id'=>$template_id,
                'createtime'=>time()
            );
            M('auth_applog')->data($data)->add();
        }

        $this->ajaxReturn ($check,'JSON');

    }

    /**
     * 获取体验码
     * @return string
     */
    public function getexperience(){

        $appid = I('post.appid','','htmlspecialchars');

        $accessToken = $this->refreshtoken($appid);
        $url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token=$accessToken";

        $filename1 = time().'.jpg';
        $user_path = 'Public/wechet';

       $file =  $this->getImage($url,$user_path,$filename1);

        $this->ajaxReturn ($file,'JSON');

    }

    /**
     * 提交审核
     * @param $user
     * @param $pid
     * @return array|mixed
     */
    public function submitaudit(){

        $appid = I('post.appid','','htmlspecialchars');
        $appname = I('post.appname','','htmlspecialchars');

        $redis = new Redis();

        $getwxcategory = $this->getwxcategory($appid);
        $getwxpages = $this->getwxpages($appid);
        if($getwxcategory[errcode]===0&&$getwxpages[errcode]===0){
            $accessToken = $this->refreshtoken($appid);

            $url = "https://api.weixin.qq.com/wxa/submit_audit?access_token=$accessToken";
            $postdata = array(
                'item_list' => array(
                    array(
                        'address' => $getwxpages[page_list][0],
                        'tag'   => $appname,
                        'first_class' => $getwxcategory[category_list][0][first_class],
                        'second_class' => $getwxcategory[category_list][0][second_class],
                        'first_id' => $getwxcategory[category_list][0][first_id],
                        'second_id' =>$getwxcategory[category_list][0][second_id],
                        'title' => '首页',
                    ),

                ));

            $postdata = json_encode($postdata,JSON_UNESCAPED_UNICODE);
            $result = $this->getcomponent($url,$postdata);

            $authname = $appid.'submitaudit';
            $redis->set($authname,$result,30*24*3600);

            $this->ajaxReturn ($result,'JSON');
        }else{
            if($getwxcategory[errcode] != 0){
                $data = array(
                    'errcode'=>$getwxcategory[errcode],
                );
            }
            if($getwxpages[errcode] != 0){
                $data = array(
                    'errcode'=>$getwxpages[errcode],
                );
            }

            $this->ajaxReturn ($data,'JSON');
        }

    }

    /**
     * 撤回审核
     */
    public function undocodeaudit($appid){

        $accessToken = $this->refreshtoken($appid);
        $url = "https://api.weixin.qq.com/wxa/undocodeaudit?access_token=$accessToken";

        $res = $this->curlget($url);

        $this->ajaxReturn ($res,'JSON');

    }

    /**
     * 发布小程序
     * @param $appid
     */
    public function release(){

        $appid = I('post.appid','','htmlspecialchars');

        $accessToken = $this->refreshtoken($appid);
        $url = "https://api.weixin.qq.com/wxa/release?access_token=$accessToken";

        $data = array();

        $res = $this->getcomponent($url,json_encode($data));

        $this->ajaxReturn ($res,'JSON');

    }

    /**
     * 获取最后审核状态
     * @param $appid
     */
    public function get_latest_auditstatus($appid){

        $redis = new Redis();

        $accessToken = $this->refreshtoken($appid);
        $url = "https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=$accessToken";

        $res = $this->curlget($url);

        $name = $appid.'get_latest_auditstatus';

        $redis->set($name,$res,30*24*3600);

        return $res;
    }

    /**
     * 获取小程序页数
     */
    private function getwxpages($appid){

            $accessToken = $this->refreshtoken($appid);
            $url = "https://api.weixin.qq.com/wxa/get_page?access_token=$accessToken";
            $ret = $this->curlget($url);
            return $ret;
    }

    /**
     * 获取小程序类型
     */
    private function getwxcategory($appid){

        $accessToken = $this->refreshtoken($appid);
        $url = "https://api.weixin.qq.com/wxa/get_category?access_token=$accessToken";
        $ret = $this->curlget($url);

        return $ret;

    }




}